package com.alienlab.finder.service.impl;

import com.alienlab.finder.domain.AppUser;
import com.alienlab.finder.domain.Relationship;
import com.alienlab.finder.repository.AppUserRepository;
import com.alienlab.finder.repository.RelationshipRepository;
import com.alienlab.finder.service.CheckTaskService;
import com.alienlab.finder.domain.CheckTask;
import com.alienlab.finder.repository.CheckTaskRepository;
import com.alienlab.finder.service.dto.CheckTaskDTO;
import com.alienlab.finder.service.dto.globalData;
import com.alienlab.finder.web.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Service Implementation for managing CheckTask.
 */
@Service
@Transactional
public class CheckTaskServiceImpl implements CheckTaskService {

    private final Logger log = LoggerFactory.getLogger(CheckTaskServiceImpl.class);

    private final CheckTaskRepository checkTaskRepository;
    private final AppUserRepository appUserRepository;
    private final RelationshipRepository relationshipRepository;

    public CheckTaskServiceImpl(RelationshipRepository relationshipRepository,AppUserRepository appUserRepository,CheckTaskRepository checkTaskRepository) {
        this.checkTaskRepository = checkTaskRepository;
        this.appUserRepository = appUserRepository;
        this.relationshipRepository = relationshipRepository;
    }

    /**
     * Save a checkTask.
     *
     * @param checkTask the entity to save
     * @return the persisted entity
     */
    @Override
    public CheckTask save(CheckTask checkTask) {
        log.debug("Request to save CheckTask : {}", checkTask);
        return checkTaskRepository.save(checkTask);
    }

    /**
     * Get all the checkTasks.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public Page<CheckTask> findAll(Pageable pageable) {
        log.debug("Request to get all CheckTasks");
        return checkTaskRepository.findAll(pageable);
    }


    /**
     * Get one checkTask by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<CheckTask> findOne(Long id) {
        log.debug("Request to get CheckTask : {}", id);
        return checkTaskRepository.findById(id);
    }

    /**
     * Delete the checkTask by id.
     *
     * @param id the id of the entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete CheckTask : {}", id);
        checkTaskRepository.deleteById(id);
    }

    @Override
    public CheckTask creatTask(String admin_open_id, String guest_open_id,String origin_x,String origin_y) throws Exception {

        AppUser main_appUser = appUserRepository.findByOpenId(admin_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+admin_open_id+"的用户");
        }
        AppUser second_appUser = appUserRepository.findByOpenId(guest_open_id);
        if (second_appUser==null){
            throw new Exception("未查找到opden_id为:"+guest_open_id+"的用户");
        }
        CheckTask checkTask = new CheckTask();
        checkTask.setAdminOpenId(admin_open_id);
        checkTask.setGuestOpenId(guest_open_id);
        checkTask.setOrigin_x(origin_x);
        checkTask.setOrigin_y(origin_y);
        checkTask.setStartTime(ZonedDateTime.now());
        checkTask.setStatesFlag("1");
        Relationship relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(admin_open_id,guest_open_id);
        if ("".equals(relationship.getDistanceSize()) || relationship.getDistanceSize()==null){
            checkTask.setDistance("200");
        }else{
            checkTask.setDistance(relationship.getDistanceSize());
        }

        checkTask = checkTaskRepository.save(checkTask);
        if (globalData.websocketmap.get(guest_open_id.toLowerCase())==null){
            System.out.println("该用户不在线，不可以进行监控");
        }else {
            WebSocketServer.SendMessage(globalData.websocketmap.get(guest_open_id.toLowerCase()),"开启任务id:"+checkTask.getId());

        }
        return checkTask;
    }

    @Override
    public CheckTask stopTask(Long task_id) throws Exception {
        CheckTask checkTask = checkTaskRepository.findById(task_id).orElse(null);
        if (checkTask==null){
            throw new Exception("未查到task_id为:"+task_id+"的监控任务");

        }else {
            if ("0".equals(checkTask.getStatesFlag())){
                throw new Exception("task_id为:"+task_id+"的监控任务已经停止，不可再次停止任务");
            }
            checkTask.setStatesFlag("0");
            checkTask.setEndTime(ZonedDateTime.now());
            checkTask = checkTaskRepository.save(checkTask);
            WebSocketServer.SendMessage(globalData.websocketmap.get(checkTask.getGuestOpenId().toLowerCase()),"结束任务id:"+checkTask.getId());

        }
        return checkTask;
    }

    @Override
    public CheckTask addTaskWarning(Long task_id, Long warning_id) throws Exception {
        CheckTask checkTask = checkTaskRepository.findById(task_id).orElse(null);
        if (checkTask==null){
            throw new Exception("未查到task_id为:"+task_id+"的监控任务");

        }else {
            if ("0".equals(checkTask.getStatesFlag())){
                throw new Exception("task_id为:"+task_id+"的监控任务已经停止，不可更新任务状态");
            }
            checkTask.setWarningId(warning_id);
            checkTask = checkTaskRepository.save(checkTask);

        }
        return checkTask;
    }

    @Override
    public List<CheckTaskDTO> guestChecktaskList(String guest_open_id) throws Exception {
        AppUser second_appUser = appUserRepository.findByOpenId(guest_open_id);
        if (second_appUser==null){
            throw new Exception("未查找到opden_id为:"+guest_open_id+"的用户");
        }
        List<CheckTaskDTO> checkTaskDTOList = new ArrayList<>();
        List<CheckTask> checkTaskList = checkTaskRepository.findByGuestOpenIdOrderByStartTimeDesc(guest_open_id);
        for (int i = 0; i < checkTaskList.size(); i++) {
            CheckTaskDTO checkTaskDTO = new CheckTaskDTO();
            String admin_openid = checkTaskList.get(i).getAdminOpenId();
            String nickname = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(guest_open_id,admin_openid).getNickname();
            if ("".equals(nickname) || nickname==null){
                checkTaskDTO.setUserName(appUserRepository.findByOpenId(admin_openid).getWechatname());
            }else {

                checkTaskDTO.setUserName(nickname);
            }
            checkTaskDTO.setHeadImage(appUserRepository.findByOpenId(admin_openid).getHeadimage());
            checkTaskDTO.setCheckTask(checkTaskList.get(i));
            checkTaskDTOList.add(checkTaskDTO);
        }

        return checkTaskDTOList;
    }

    @Override
    public List<CheckTaskDTO> adminChecktaskList(String admin_open_id) throws Exception {

        AppUser main_appUser = appUserRepository.findByOpenId(admin_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+admin_open_id+"的用户");
        }
        List<CheckTaskDTO> checkTaskDTOList = new ArrayList<>();
        List<CheckTask> checkTaskList = checkTaskRepository.findByAdminOpenIdOrderByStartTimeDesc(admin_open_id);

        for (int i = 0; i < checkTaskList.size(); i++) {
            CheckTaskDTO checkTaskDTO = new CheckTaskDTO();
            String guest_openid = checkTaskList.get(i).getGuestOpenId();
            String nickname = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(admin_open_id,guest_openid).getNickname();
            if ("".equals(nickname) || nickname==null){
                checkTaskDTO.setUserName(appUserRepository.findByOpenId(guest_openid).getWechatname());
            }else {
                checkTaskDTO.setUserName(nickname);
            }
            checkTaskDTO.setHeadImage(appUserRepository.findByOpenId(guest_openid).getHeadimage());
            checkTaskDTO.setCheckTask(checkTaskList.get(i));
            checkTaskDTOList.add(checkTaskDTO);
        }

        return checkTaskDTOList;
    }

    @Override
    public List<String> getMonitoredList(String admin_open_id) throws Exception {
        List<String> monitoredList = new ArrayList<>();
        AppUser main_appUser = appUserRepository.findByOpenId(admin_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+admin_open_id+"的用户");

        }

        List<CheckTask> checkTaskList = checkTaskRepository.findByAdminOpenIdOrderByStartTimeDesc(admin_open_id);
        if (checkTaskList.size()>0){
            for (int i = 0; i <checkTaskList.size() ; i++) {
                String flag = checkTaskList.get(i).getStatesFlag();
                if ("1".equals(flag)){
                    monitoredList.add(checkTaskList.get(i).getGuestOpenId());
                }
            }

        }

        return monitoredList;
    }

    @Override
    public String taskIsDoing(String admin_open_id, String guest_open_id) {

        String taskId = "0";
        List<CheckTask> checkTaskList = checkTaskRepository.findByAdminOpenIdAndGuestOpenIdOrderByStartTimeDesc(admin_open_id, guest_open_id);
        if (checkTaskList.size()>0){
            for (int i = 0; i < checkTaskList.size(); i++) {
                if ("1".equals(checkTaskList.get(i).getStatesFlag())){
                    taskId = String.valueOf(checkTaskList.get(i).getId()) ;
                }
            }

        }

        return taskId;
    }

    @Override
    public String getDoingtask(String guest_open_id) {
        String taskid="0";
        List<CheckTask> checkTaskList = checkTaskRepository.findByGuestOpenIdOrderByStartTimeDesc(guest_open_id);
        if (checkTaskList.size()>0){
            for (int i = 0; i < checkTaskList.size(); i++) {
                if ("1".equals(checkTaskList.get(i).getStatesFlag())){
                    taskid = String.valueOf(checkTaskList.get(i).getId());
                }

            }
        }

        return taskid;
    }


}
